import React, { useEffect, useState } from 'react';
import { getAttachmentsByBlogId, uploadFile, downloadFile } from '../../util/actions/attachmentAction';
import { List, Button, Spin, Upload, message, Image } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

const AttachmentDetail = ({ blogId }) => {
  const [attachments, setAttachments] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchAttachments = async () => {
    try {
      const attachmentData = await getAttachmentsByBlogId(blogId);
      const formattedData = attachmentData.map((attachment) => ({
        ...attachment,
        // file_url: `${process.env.NEXT_PUBLIC_API_BASE_URL.replace('api', '')}/${attachment.file_path.replace(/\\/g, '/')}`
         file_url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/${attachment.file_path.replace(/\\/g, '/')}`
      }));
      setAttachments(formattedData);
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };


const handleUploadFile = async ({ file }) => {
    try {
      const response = await uploadFile(blogId, file);
      console.log(response);  // 打印 response 内容以调试
  
      const filePath = response.file.path;
      if (!filePath) {
        throw new Error('File path is missing in the response');
      }
  
      const formattedResponse = {
        ...response.file,
        file_url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/${filePath.replace(/\\/g, '/')}`
      };
  
      setAttachments([...attachments, formattedResponse]);
      message.success('上传成功');
    } catch (error) {
      console.error(error);
      message.error(`上传失败: ${error.message}`);
    }
  };
  
// const handleUploadFile = async ({ file }) => {
//     try {
//       // 上传文件
//       const response = await uploadFile(blogId, file);
      
//       // 构建带有文件 URL 的响应对象
//       const formattedResponse = {
//         ...response,
//         file_url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/${response.file_path.replace(/\\/g, '/')}`

//       };
      
//       // 将新的附件添加到现有附件列表中
//       setAttachments([...attachments, formattedResponse]);
  
//       // 显示上传成功的消息
//       message.success('上传成功');
//     } catch (error) {
//       // 如果上传失败，记录错误并显示错误消息
//       console.error(error);
//       message.error('上传失败');
//     }
//   };
  const handleDownloadFile = (filename) => {
    downloadFile(filename).catch((error) => console.error(error));
  };

  useEffect(() => {
    fetchAttachments();
  }, [blogId]);

  if (loading) return <Spin />;

  return (
    <div>
      <h2>附件</h2>
      <List
        dataSource={attachments}
        renderItem={(attachment) => (
          <List.Item
            actions={[
              <Button onClick={() => handleDownloadFile(attachment.file_name)}>下载</Button>
            ]}
          >
            <List.Item.Meta
              avatar={<Image width={100} src={attachment.file_url} />}
            //   title={attachment.file_name}
            />
          </List.Item>
        )}
      />
      <Upload
        customRequest={handleUploadFile}
        showUploadList={false}
      >
        <Button icon={<UploadOutlined />}>上传文件</Button>
      </Upload>
    </div>
  );
};

export default AttachmentDetail;

// import React, { useEffect, useState } from 'react';
// import { getAttachmentsByBlogId, uploadFile, downloadFile } from '../../util/actions/attachmentAction';
// import { List, Button, Spin, Upload, message, Image } from 'antd';
// import { UploadOutlined } from '@ant-design/icons';

// const AttachmentDetail = ({ blogId }) => {
//   const [attachments, setAttachments] = useState([]);
//   const [loading, setLoading] = useState(true);

//   const fetchAttachments = async () => {
//     try {
//       const attachmentData = await getAttachmentsByBlogId(blogId);
//       setAttachments(attachmentData);
//       setLoading(false);
//     } catch (error) {
//       console.error(error);
//       setLoading(false);
//     }
//   };

//   const handleUploadFile = async ({ file }) => {
//     try {
//       const response = await uploadFile(blogId, file);
//       setAttachments([...attachments, response]);
//       message.success('上传成功');
//     } catch (error) {
//       console.error(error);
//       message.error('上传失败');
//     }
//   };

//   const handleDownloadFile = (filename) => {
//     downloadFile(filename).catch((error) => console.error(error));
//   };

//   useEffect(() => {
//     fetchAttachments();
//   }, [blogId]);

//   if (loading) return <Spin />;

//   return (
//     <div>
//       <h2>附件</h2>
//       <List
//         dataSource={attachments}
//         renderItem={(attachment) => (
//           <List.Item
//             actions={[
//               <Button onClick={() => handleDownloadFile(attachment.filePath)}>下载</Button>
//             ]}
//           >
//             <List.Item.Meta
//               avatar={<Image width={50} src={attachment.filePath} />}
//               title={attachment.filename}
//             />
//           </List.Item>
//         )}
//       />
//       <Upload
//         customRequest={handleUploadFile}
//         showUploadList={false}
//       >
//         <Button icon={<UploadOutlined />}>上传文件</Button>
//       </Upload>
//     </div>
//   );
// };

// export default AttachmentDetail;

